package com.lkei.shiro.realms;


import com.lkei.entity.Perms;
import com.lkei.entity.User;
import com.lkei.service.UserService;
import com.lkei.utils.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**自定义realm*/
public class CustomeRealm extends AuthorizingRealm {



    /**认证信息*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //根据身份信息
        String principal = (String) authenticationToken.getPrincipal();
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        /**ObjectUtils.isEmpty(user)代表判断user对象是否为空，为空则返回true*/
        if(!ObjectUtils.isEmpty(user)){

            return new SimpleAuthenticationInfo(user.getAccount(),user.getPassword(),this.getName());
        }
        return null;
    }

    /**授权信息*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();

        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findRoleByUserName(primaryPrincipal);

        //根据主身份信息获取角色和权限信息
        //CollectionUtils.isEmpty(roles)代表判断roles集合是否为空，为空则返回true
        //赋值授权角色
        if (!CollectionUtils.isEmpty(user.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getRolename());

                //权限信息
                List<Perms> perms = userService.findPermsByRoleId(role.getId());
//                System.out.println(perms);
                if (!CollectionUtils.isEmpty(perms)){
                    perms.forEach(perm ->{
                        simpleAuthorizationInfo.addStringPermission(perm.getPermsname());
                    });
                }
            });


            return simpleAuthorizationInfo;
        }

        return null;
    }


}
